#!/bin/bash

PATCH=patch

case $1 in
patch)
	PATCH_OPT="-sp1"
	;;
unpatch)
	PATCH_OPT="-Rsp1"
	;;
*)
	echo Usage: "$0 <patch|unpatch>"
	exit 1
	;;
esac

function use_patch_or_exit() {
	$PATCH $PATCH_OPT < $1
	if [ $? -ne 0 ]; then exit 2; fi
}

# patch binutils (using the files provided in the Release Files, and repeat for any additional patches or LTS files)
cd ../binutils/sources
echo =====$1 binutils=====
# Patch binutils to bring it to Release 20120406 (still at 20120406)
use_patch_or_exit "../../mspgcc/normal_patchs/msp430-binutils-2.21.1a-20120406.patch"

# Return to the build directory
cd ../..
 
# patch GCC to bring it up to Release 20120406
cd gcc/sources
echo =====$1 gcc=====
gcc_patchs=(
"../../mspgcc/normal_patchs/msp430-gcc-4.6.3-20120406.patch" 
"../../mspgcc/lts_patchs/msp430-gcc-4.6.3-20120406-sf3540953.patch" 
"../../mspgcc/lts_patchs/msp430-gcc-4.6.3-20120406-sf3559978.patch" )
idx=0
end_idx=-1
if [ $1 = "patch" ]; then
	let end_idx=${#gcc_patchs[@]}
else
	let idx=${#gcc_patchs[@]}-1
fi
while [ $idx -ne $end_idx ]; do
	use_patch_or_exit ${gcc_patchs[$idx]}
	if [ $? -ne 0 ]; then exit 2; fi
	if [ $1 = "patch" ]; then
		let idx++
	else
		let idx--
	fi
done

# Return to the build directory
cd ../..

# Patch GDB to bring it to release 20120406
cd gdb/sources
echo =====$1 gdb=====
use_patch_or_exit "../../mspgcc/normal_patchs/msp430-gdb-7.2a-20111205.patch"

exit 0
